import socket
import time
import sys
class FileSender:
    def __init__(self,parent):
        print("file sender init")
        self.progressbar = parent.progressbar
        self.speedShow = parent.speedShow
        # self.filepath = parent.path
        self.addr = parent.addr
        ##建立TCP socket
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print("sender try to connect "+str(self.addr))
        while True:
            try:
                self.s.connect(self.addr['addr'])
                break
            except Exception:
                continue
        print("sender connect receiver success")
        while True:
            if parent.canSend:
                print("can send")
                self.filepath = parent.path
                self.send(10240)
                parent.canSend=False
    
    def send(self,length):
        # print("a new sending")
        myfile = open(self.filepath,"rb")
        fileBytes = myfile.read()
        start = 0
        filename = self.filepath.split("/")[-1]
        ###向对方发送文件名称
        # print("sending filename")
        self.s.send(filename.encode("utf-8"))
        # print("sending filename ok")
        ###监测对方的filename返回值
        while True:
            data = self.s.recv(10240)
            if data==b"filename ok":
                print("filename send ok")
                break
        ###开始文件发送
        starttime = time.time()
        count=0
        while True:
            count+=1
            sendBytes = fileBytes[start:start+length]
            if sendBytes:
                self.s.send(sendBytes)
                if count%100==0:
                    speed = 0
                    try:
                        currenttime = time.time()
                        dertaTime = (currenttime-starttime)
                        speed = length/dertaTime
                        self.speedShow['text']="传输速度:%fBytes/s"%speed
                        starttime = time.time()
                    except Exception:
                        pass
                    # print(speed)
                start += length
                jindu = start/len(fileBytes)*100
                self.progressbar['value']=jindu
                # print(jindu)
            else:
                break
            while True:
                data = self.s.recv(length)
                if data == b'receive ok':
                    break
        self.s.send("file send finish!".encode("utf-8"))
        print("file send finish!")
    
if __name__ == "__main__":
    myFileSender = FileSender("./1.docx",("127.0.0.1",913))
    myFileSender.send(10240)
        

